package org.starsource.forum.client.view;

import org.starsource.forum.client.web.UserService;
import org.starsource.forum.client.web.UserServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * A simple example of an 'about' dialog box.
 */
public class PasswordUpdateDialog extends DialogBox {
	private final UserServiceAsync userService = GWT.create(UserService.class);

	interface Binder extends UiBinder<Widget, PasswordUpdateDialog> { }
	private static final Binder binder = GWT.create(Binder.class);

	@UiField PasswordTextBox password;
	@UiField PasswordTextBox password2;
	@UiField Button submitButton;
	@UiField Button cancelButton;
	@UiField Element tips;

	public PasswordUpdateDialog() {
		setWidget(binder.createAndBindUi(this));

		setAnimationEnabled(true);
		setGlassEnabled(true);

		password.addKeyPressHandler(new KeyPressHandler() {

		@Override
		public void onKeyPress(KeyPressEvent event) {
			if (event.getCharCode() == KeyCodes.KEY_ENTER) {
				password2.setFocus(true);
			}
		}
			
		});
		
		password2.addKeyPressHandler(new KeyPressHandler() {

		@Override
		public void onKeyPress(KeyPressEvent event) {
			if (event.getCharCode() == KeyCodes.KEY_ENTER) {
				updatePassword();
			}
		}
			
		});

		setText("请修改密码");
		tips.setInnerText("密码至少为6位");
	}

	@UiHandler("submitButton")
	void onSubmitClicked(ClickEvent event) {
		updatePassword();
	}
	
	@UiHandler("cancelButton")
	void onCancelClicked(ClickEvent event) {
		hide();
	}

	public void focus() {
		password.setFocus(true);
	}
	public boolean validate() {
		if (password.getText().length() <6) {
			tips.setInnerText("密码长度至少为6位");
			return false;
		}
		if (!password.getText().equals(password2.getText())) {
			tips.setInnerText("两次输入的密码不一致，请确认是否正确输入。");
			return false;
		}
		return true;
	}

	private void updatePassword() {
		if (!validate()) {
			return;
		}
		submitButton.setEnabled(false);
		userService.changePassword(password.getText(), new AsyncCallback<Void>() {
	
			@Override
			public void onFailure(Throwable caught) {
					tips.setInnerText(caught.getMessage());
					submitButton.setEnabled(true);
			}
	
			@Override
			public void onSuccess(Void result) {
				hide();
					submitButton.setEnabled(true);
			}
		});
	}
}
